using GSN.Senders;

namespace GSN.Mail.Messages
{
    public class Message
    {
        public string subject = null;
        public string from = null;
        public string messageId = null;
        public string body = "";

        /*
        public static Message createNew()
        {
            return new Message();
        }*/

        public Message(IMessageBuilder builder)
        {
            builder.set(this);
        }


        private string getSummary()
        {
            string smsTemplate = null;
            string summary = null;

            try
            {
               smsTemplate = GSNConfig.getConfigItem(GSNConfig.GSN_CONFIG_SMS_TEMPLATE);
            }
            catch (ConfigException)
            {
            }

            if (smsTemplate == null)
            {
                summary = string.Format("You've got mail from {0}. {1}: {2}", from, subject, body);
            }
            else
            {
                summary = smsTemplate;
                summary = MessageMacrosReplacer.replaceMacro(summary, "%From%", from);
                summary = MessageMacrosReplacer.replaceMacro(summary, "%Subject%", subject);
                summary = MessageMacrosReplacer.replaceMacro(summary, "%Body%", body);
            }

            return summary;
        }

        public void send(ISMSSender sender)
        {
            string text = getSummary();

            // enforce length limit
            int maxLen = 155;
            if (text.Length > maxLen)
                text = text.Remove(maxLen);
            // check if there are unicode chars
            int unicodeMaxLen = 70;
            int utf8len = System.Text.Encoding.UTF8.GetByteCount(text);
            if (utf8len != text.Length && text.Length > unicodeMaxLen)
                text = text.Remove(unicodeMaxLen);

            Logger.log("Sending SMS: " + text);
            sender.send(GSNConfig.getConfigItem(GSNConfig.GSN_CONFIG_PHONE), text);
        }
    }
}
